<template>
    <div class="c-form-item">
        <!-- label标签-->
        <label v-if="label">{{label}}</label>
        <slot></slot>
        <!-- 错误校验信息-->
        <p v-if="error" class="error">{{error}}</p>
    </div>
</template>

<script>
    import Schema from "async-validator"

    export default {
        name: "c-form-item",
        inject: ['Form'],
        props: {
            label: {
                type: String,
                default: "",
            },
            prop: {
                type: String
            }
        },
        data() {
            return {
                error: "",
            }
        },
        methods: {
            validator() {
                //拿到Form的rule对象中prop对应的rule
                const rule = this.Form.rules[this.prop];
                console.log(rule)

                //拿到Form的model对象中prop对应的值
                const value = this.Form.model[this.prop];
                console.log(value)

                // Schema定义规则 value:规则 生成规则的实例对象
                const schema = new Schema({[this.prop]: rule})

                //schema.validate 传入 key和value 去比对定义的规则，在callback中返回比对结果！
               return schema.validate({[this.prop]: value}, error => {
                    if (error) {
                        this.error = error[0].message
                    } else {
                        this.error = "";
                    }
                })
            }
        },
        mounted() {
            this.$on("validate", () => {
                console.log(1)
                this.validator();
            })
        }
    }
</script>

<style scoped>
    label {
        font-size: .6rem;
    }

    .error {
        transition: all 2s;
        font-size: .5rem;
        color: red;
    }
</style>